//
//  SDPhtoInfoViewController.m
//  SKinDiary
//
//  Created by pcyang on 16/7/16.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDPhotoInfoViewController.h"
#import "SDSelectPaientViewcontroller.h"
#import "SDPhotoPaientCell.h"
#import "SDPhotoPositionCell.h"
#import "SDCameraStatusCell.h"
#import "SDPhotoModelCell.h"
#import "SDPhotoMarkCell.h"
#import "SDPhotoCustomTagCell.h"
#import "SDPhotoInfo.h"
#import "SDPaientInfoItem.h"
#import "VPCommentInputBar.h"
#import "SDPaientInfoMgr.h"

@interface SDPhotoInfoViewController()<UITableViewDataSource, UITableViewDelegate,VPCommentInputBarDelegate,UITextViewDelegate>
@property(nonatomic,strong)UITableView* tableView;
@property(nonatomic,strong)SDPaientInfoItem* paientInfo;
@property (nonatomic,strong)SDPhotoCustomTagCell* customTagCell;
@property (nonatomic,strong)SDPhotoModelCell* modeCell;
@property (nonatomic,strong)SDPhotoPositionCell* postionCell;
@property (nonatomic,strong)SDCameraStatusCell* stateCell;
@property (nonatomic, strong) SDPhotoMarkCell * operatedCell;

@property(nonatomic,assign)    CGFloat bottom;
@property(nonatomic,assign)    CGPoint oldOffset;
@property(nonatomic,assign)    CGFloat keyboardTop;

@property (nonatomic, strong) SDPhotoInfo *photoInfo;
@end

@implementation SDPhotoInfoViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self registerForKeyboardNotifications];

    [self initViews];
    [self initData];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (_locateCommentArea) {
        [_operatedCell.textView becomeFirstResponder];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _locateCommentArea = NO;
}

-(void)initData
{
    if (_photoInfoArray.count == 0) {
        return;
    }
    _photoInfo = [_photoInfoArray objectAtIndex:0];
    if (_photoInfo.patientId  > 0 ) {
        NSArray* paientList = [[SDPaientInfoMgr shareAGDatabaseManager] select:[SDPaientInfoItem class] tableName:kPaientTableName where:[NSString stringWithFormat:@"pId = %ld",_photoInfo.patientId]];
        if (CHECK_VALID_ARRAY(paientList)) {
            _paientInfo = [paientList objectAtIndex:0];
        }
    }
}

- (void)initViews
{
    BOOL naviHidden = [self navigationBarHidden];
    if (!naviHidden && self.navBar != nil)
    {
        [self.navBar setTitle:@"添加标注"];
        UIImage* addImg = LOAD_IMAGE_USE_CACHE_INBUNDLE(DefaultBundle, @"actionbar_btn_back.png");
        [self.navBar customNaviLeftButton:self action:@selector(onBack:) image:addImg];
        [self.navBar customNaviRightButton:self action:@selector(onStore:) title:@"存储"];
    }
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _tableView = [[UITableView alloc] initWithFrame:autoRectTableViewHaveBar(YES) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor colorWithRGB:0xf9fafc];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
}

- (BOOL)navigationBarHidden
{
    return NO;
}

- (void)onBack:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onStore:(id)sender
{
    __block BOOL success = false;
    
    [_photoInfoArray enumerateObjectsUsingBlock:^(SDPhotoInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SDPhotoInfo *photoInfo = obj;
        if (_paientInfo != nil) {
            photoInfo.patientId = _paientInfo.pId;
        }
        
        BOOL isChanged = NO;
        NSArray* tags = [_customTagCell getSelectedTagItems];
        if (CHECK_VALID_ARRAY(tags)) {
            NSString* newValue = [tags componentsJoinedByString:@","];
            if (![newValue isEqualToString: photoInfo.tag]) {
                isChanged = YES;
            }
            photoInfo.tag =  [tags componentsJoinedByString:@","];
        }
        
        tags = [_modeCell getSelectedTagItems];
        if (CHECK_VALID_ARRAY(tags)) {
            NSString* newValue = [tags componentsJoinedByString:@","];
            if (![newValue isEqualToString: photoInfo.mode]) {
                isChanged = YES;
            }
            photoInfo.mode =  [tags componentsJoinedByString:@","];
        }
        
        tags = [_postionCell getSelectedTagItems];
        if (CHECK_VALID_ARRAY(tags)) {
            NSString* newValue = [tags componentsJoinedByString:@","];
            if (![newValue isEqualToString: photoInfo.position]) {
                isChanged = YES;
            }
            photoInfo.position =  [tags componentsJoinedByString:@","];
        }
        
        tags = [_stateCell getSelectedTagItems];
        if (CHECK_VALID_ARRAY(tags)) {
            NSString* newValue = [tags componentsJoinedByString:@","];
            if (![newValue isEqualToString: photoInfo.status]) {
                isChanged = YES;
            }
            photoInfo.status =  [tags componentsJoinedByString:@","];
        }
        NSString* newValue = _operatedCell.textView.text;
        if (![newValue isEqualToString: photoInfo.comments]) {
            isChanged = YES;
        }
        
        if (isChanged) {
            photoInfo.updateTime = [[NSDate date] formattedString];
        }
        photoInfo.comments = _operatedCell.textView.text;
        
        success = [[SDPaientInfoMgr shareAGDatabaseManager] update:photoInfo tableName:kPhotoTableName where:[NSString stringWithFormat:@"id = %d",photoInfo.id]];

    }];
    
    if (success) {
        // 清除连拍缓存
        [[SDPhotoArray shareInstanse] removeAllPhoto];
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

-(void)onAddTagButtonClicked:(id)sender
{
    if ([_customTagCell.tagItemsArray count] >= 2) {
        [SDAlertManagement showNormalErrorAlert:@"最多可以添加两个标签"];
        return;
    }
    
    [[VPCommentInputBar sharedInstance] setMaxLength:8];
    [VPCommentInputBar showInputBarAddedTo:self.view delegate:self placeHolderText:@"添加新的标签..."];

}

- (void) registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)unregNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

#pragma mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    if (row == 0) {
         return kPhotoPaientCellHeight;
    } else if(row == 1){
        return kPhotoCustomTagCellHeight;
    }else if(row == 2){
        return [SDPhotoModelCell getRequiredCellHeight:[SDPhotoModelCell getTagItems]];
    }else if(row == 3){
        return [SDPhotoPositionCell getRequiredCellHeight:[SDPhotoPositionCell getTagItems]];
    } else if(row == 4){
        return [SDCameraStatusCell getRequiredCellHeight:[SDCameraStatusCell getTagItems]];
    } else if(row == 5){
        return kPhotoMarkCellHeight;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = [indexPath row];
    
    if (row == 0) {
        SDPhotoPaientCell* cell = nil;
        static NSString* identifier = @"SDPhotoPaientCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if( cell == nil )
        {
            cell = [[SDPhotoPaientCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        [cell setCellData:_paientInfo];
        
        return cell;
    }else if (row == 1) {
        SDPhotoCustomTagCell* cell = nil;
        static NSString* identifier = @"SDPhotoCustomTagCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if( cell == nil )
        {
            cell = [[SDPhotoCustomTagCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            [cell.addButton addTarget:self action:@selector(onAddTagButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
            _customTagCell = cell;
        }
        [cell setCellData:_photoInfo.tag];
        
        return cell;
    }else if (row == 2) {
        SDPhotoModelCell* cell = nil;
        static NSString* identifier = @"SDPhotoModelCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if( cell == nil )
        {
            cell = [[SDPhotoModelCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            _modeCell = cell;
        }
        [cell setCellData:_photoInfo.mode];
        
        return cell;
    }else if (row == 3) {
        SDPhotoPositionCell* cell = nil;
        static NSString* identifier = @"SDPhotoPostionCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if( cell == nil )
        {
            cell = [[SDPhotoPositionCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            _postionCell = cell;
        }
        [cell setCellData:_photoInfo.position];
        
        return cell;
    } else if (row == 4) {
        SDCameraStatusCell* cell = nil;
        static NSString* identifier = @"SDCameraStatusCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if( cell == nil )
        {
            cell = [[SDCameraStatusCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            _stateCell = cell;
        }
        [cell setCellData:_photoInfo.status];
        
        return cell;
    } else if (row == 5) {
        SDPhotoMarkCell* cell = nil;
        static NSString* identifier = @"SDPhotoMarkCell";
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if( cell == nil )
        {
            cell = [[SDPhotoMarkCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.textView.delegate  = self;
            _operatedCell = cell;
        }
        [cell setCellData:_photoInfo.comments];
        
        return cell;
    }


    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    if(row == 0){
        SDSelectPaientViewcontroller* selectPaientViewController = [[SDSelectPaientViewcontroller alloc] init];
        [self.navigationController pushViewController:selectPaientViewController animated:YES];
        
        [selectPaientViewController didSelectedItem:^(SDPaientInfoItem *item) {
            _paientInfo = item;
            _photoInfo.patientId = _paientInfo.pId;
            [self.tableView reloadData];
        }];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark- VPCommentInputBarDelegate
- (BOOL)commentInputBarShouldBeginEditing:(VPCommentInputBar *)inputBar
{
    return YES;
}

- (void)commentInputBarDidPressSendButton:(VPCommentInputBar *)inputBar
{
    NSString* content = [inputBar getTextContent];
   
    if (0 < [content length])
    {
        PhotoTagItem* tagItem = [[PhotoTagItem alloc] init];
        tagItem.title = content;
        [_customTagCell addTagItem:tagItem];
    }
}

- (void)commentInputBar:(VPCommentInputBar *)inputBar textViewDidChange:(UITextView *)textView
{

}

#pragma mark KeyboardNotification
// 键盘弹出，获得键盘高度，计算界面需要偏移的距离
- (void) keyboardWillShow:(NSNotification *) notification {
    
    CGPoint currentOffset = self.tableView.contentOffset;

    _oldOffset = currentOffset;
    NSDictionary *userInfo = [notification userInfo];
    
    // Get the origin of the keyboard when it's displayed.
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    _keyboardTop = keyboardRect.origin.y;
    
    // 计算出需要偏移的距离offset，即输入框bottom与键盘top的距离
    float offset = _bottom - _keyboardTop;
    if(offset > 0) { // offset为正，说明输入框被键盘遮挡
        NSTimeInterval animationDuration = 0.3f;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        offset += 5;
        self.tableView.contentOffset = CGPointMake(0, _oldOffset.y + offset);
        [UIView commitAnimations];
    }
}

//键盘隐藏，将视图恢复到原始状态
- (void) keyboardWillHidden:(NSNotification *) notif {
    self.tableView.contentOffset = _oldOffset;
    _bottom = 0;
}

#pragma mark - UIScrollView

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (self.operatedCell != nil) {
        [self.operatedCell.textView resignFirstResponder];
    }
}

#pragma mak - UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    //CGRect rect =  CGRectMake(self.operatedCell.left, self.operatedCell.top, self.operatedCell.width, self.operatedCell.height);
   // self.userTapOffset = CGPointMake(0, ceil(rect.origin.y+rect.size.height));
    
    if ([_operatedCell.textView isEqual:textView])
    {
        UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
        CGRect rect1 = [textView convertRect: textView.bounds toView:window]; // 在屏幕上的坐标
        _bottom = rect1.origin.y + rect1.size.height; // 获得输入框底部在屏幕上的绝对位置

    }

    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
}

- (void)textViewDidEndEditing:(UITextView *)textView {
   
}

- (void)textViewDidChange:(UITextView *)textView
{
    if ([_operatedCell.textView isEqual:textView]) {
        if (textView.text.length > 0 ) {
            _operatedCell.placeHolderLabel.hidden = YES;
        } else {
            _operatedCell.placeHolderLabel.hidden = NO;
        }
    } else
    {
        
    }
}
@end
